<?php

namespace app\model\system;

use app\model\BaseModel;

/**
 *
 */
class SysDept extends BaseModel
{
  protected $table = "sys_dept";

  public function children()
  {
    return $this->hasMany(SysDept::class, 'parent_id', 'id');
  }

  public static function optionTree(int $parentId = 0): array
  {
    $deptTree = [];
    $rootDept = self::where("is_deleted", 0)->where('parent_id', $parentId)->select();
    if (!$rootDept->isEmpty()) {
      foreach ($rootDept as $dept) {
        $node =  ["value" => (int) $dept->id, "label" => $dept->name];
        $children = $dept->optionTree($dept->id);
        if ($children) {
          $node["children"] = $children;
        }
        $deptTree[] = $node;
      }
    }
    return $deptTree;
  }

  public static function deptTree(int $parentId = 0, ?int $status = null, ?string $keywords = null): array
  {
    $deptTree = [];

    $rootDept = self::where("is_deleted", 0)->where('parent_id', $parentId);
    if ($status !== null) {
      $rootDept->where('status', $status);
    }
    if ($keywords) {
      $rootDept->where('name', 'like', "%{$keywords}%");
    }
    $rootDept = $rootDept->select();
    if (!$rootDept->isEmpty()) {
      foreach ($rootDept as $dept) {
        $node = $dept->getFormArray();
        $children = $dept->deptTree($dept->id);
        if ($children) {
          $node["children"] = $children;
        }
        $deptTree[] = $node;
      }
    }
    return $deptTree;
  }


  public function getFormArray(): array
  {
    return [
      "parentId" =>(int) $this->parentId,
      "id" => (int)$this->id,
      "name" => $this->name,
      "code" => $this->code,
      "status" => $this->status,
      "sort" => $this->sort,
    ];
  }

  public function toArray(array $merges = []): array
  {
    $modeArray = $this->getFormArray() + [
      "children" => []
    ];
    return $this->merge($modeArray, $merges);
  }
}
